//
//  VideoDetailVC.m
//  Brand
//
//  Created by Faker on 4/24/14.
//  Copyright (c) 2014 Faker. All rights reserved.
//

#import "VideoDetailVC.h"
#import "CollectionFixedHeaderLayout.h"
#import "VideoPlayerViewController.h"
#import "config.h"
#import "Header.h"

#define DefaultTop    150
#define DefaultDur    0.5
#define OffsetY       60  //下拉超过80就滚下去

#define CellIdentifer   @"CellIdentifer"

@interface VideoDetailVC ()
@property (weak, nonatomic) IBOutlet UIView *topBgView;
@property (weak, nonatomic) IBOutlet UIView *infoView;
@property (weak, nonatomic) IBOutlet UIScrollView *myScrollView;
@property (weak, nonatomic) IBOutlet UIView *contentView;
@property (weak, nonatomic) IBOutlet UIView *mainView;

@property (weak, nonatomic) IBOutlet UILabel *scoreLabel;
@property (weak, nonatomic) IBOutlet UIButton *scoreBtn;

@property (strong, nonatomic) NSMutableArray* videoArray;

@property (strong, nonatomic) CircleScrollView* myCircleView;
@property (strong, nonatomic) NSArray* picArray;

@property (strong, nonatomic) NSArray* recommendArray;
@property (strong, nonatomic) UICollectionView* myCollectionView;

@property (assign, nonatomic) BOOL isUp; //在上还是在下面

@property (assign, nonatomic) float defaultContentTop;
@property (assign, nonatomic) float defaultScrollTop;

@property (assign, nonatomic) float detailLabelHeight;

@property (weak, nonatomic) IBOutlet UIView *guessView;
@property (weak, nonatomic) IBOutlet UIView *detailView;
@property (weak, nonatomic) IBOutlet UILabel *detailLabel;
@property (weak, nonatomic) IBOutlet UIButton *moreBtn;

@property (assign, nonatomic) BOOL isGoPlay;
@property (weak, nonatomic) IBOutlet UIButton *playBtn;
@property (weak, nonatomic) IBOutlet UIButton *shareBtn;

@property (assign, nonatomic) BOOL isDowning;

@end

@implementation VideoDetailVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setUp];
}

-(void)viewWillLayoutSubviews
{
    
}

-(void)setUp
{
    self.scoreBtn.enabled = NO;
    self.videoObj.intro = @"";
    self.isUp = YES;
    self.videoArray = [[NSMutableArray alloc]init];
    self.defaultContentTop = self.contentView.top;
    self.defaultScrollTop = self.mainView.top;
    
    self.detailLabelHeight = self.detailLabel.height;
    self.myScrollView.contentHeight = self.myScrollView.height+1;
    
    if(!self.videoObj.isReadyShow)
    {
        self.playBtn.enabled = NO;
    }
   
   //self.myScrollView.clipsToBounds = NO;
    self.infoView.clipsToBounds = NO;
   
    if(!isiPhone5)
    {
        self.contentView.height = isiOS7 ? 480 : 460;
    }
    
    if([[kHandle sharedInstance] isShowTrueView])
    {
        self.guessView.hidden = NO;
    }
    else
    {
        self.guessView.hidden = YES;
    }
    
    self.myCircleView = [[CircleScrollView alloc]initWithFrame:CGRectMake(0, 0 , 320, self.contentView.height) andPageXibName:@"VideoCircleCell"];
    self.myCircleView.delegate = self;
    self.myCircleView.isCanAuto = NO;
    [self.contentView addSubview:self.myCircleView];
    
    self.myCollectionView = [self drawCollectionViewWithFrame:CGRectMake(0, 18, self.guessView.width, self.guessView.height) andFlowLayout:[self getFlowLayout]];
    [self registerCellAndHeaderForCollectionView:self.myCollectionView];
    
    [self prepareGetData];

}

#pragma mark - 生成collectionview和布局布局管理器
-(UICollectionView*)drawCollectionViewWithFrame:(CGRect)frame andFlowLayout:(CollectionFixedHeaderLayout*)flowLayout
{
    UICollectionView* myCollectionView = [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:flowLayout];
    myCollectionView.showsVerticalScrollIndicator = NO;
    myCollectionView.showsHorizontalScrollIndicator = NO;
    myCollectionView.dataSource = self;
    myCollectionView.delegate = self;
    myCollectionView.backgroundColor = [UIColor clearColor];
    return myCollectionView;
}

-(void)registerCellAndHeaderForCollectionView:(UICollectionView*)collectionView
{
    UINib *cellNib = nil;
    cellNib = [UINib nibWithNibName:@"RecommendCell" bundle:nil];
    [collectionView registerNib:cellNib forCellWithReuseIdentifier:CellIdentifer];
    
}

//一个布局管理器只能对应一个collectionView
-(CollectionFixedHeaderLayout*)getFlowLayout
{
    CollectionFixedHeaderLayout *flowLayout = [[CollectionFixedHeaderLayout alloc] init];
    flowLayout.isFiexed = NO;
    [flowLayout setItemSize:CGSizeMake(60, 87)];
    flowLayout.minimumInteritemSpacing =0;
    flowLayout.minimumLineSpacing = 10;
    //flowLayout.headerReferenceSize = CGSizeMake(320, 30);
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 20, 0, 20);  //top left bottom right
   
    return flowLayout;
}




#pragma mark - 网络请求
-(void)prepareGetData
{
    [kApp displayWaitViewWithAllMaskView:NO];
    [self btnsDisable];
    
    NSString* url1 = [NSString stringWithFormat:@"%@videoPlay&id=%@",API_BASE,self.videoObj.episodeId];
    
    NSString* url2 = [NSString stringWithFormat:@"%@spreadApp&type=0",API_BASE];
   
   
    [[AFGetData sharedInstance] startGet:url1 andResultIsJSON:YES andCompletion:^(AFHTTPRequestOperation *operation, id responseObj, BOOL isSuccess) {
        if(isSuccess)
        {
            [self getDataSuccess:responseObj];
        }
        else{
            [self getDataError];
        }
    }];
    
    [[AFGetData sharedInstance] startGet:url2 andResultIsJSON:YES andCompletion:^(AFHTTPRequestOperation *operation, id responseObj, BOOL isSuccess) {
        if(isSuccess)
        {
            [self getRecommendSuccess:responseObj];
        }
        else
        {
            [self getRecommendError];
        }
    }];
}

#pragma mark - 推荐应用
-(void)getRecommendSuccess:(id)responseObj
{
    self.recommendArray = (NSArray*)responseObj;
    [self.guessView addSubview:self.myCollectionView];
    [self.myCollectionView reloadData];
    
}

-(void)getRecommendError
{
   
}

#pragma mark - 普通数据
-(void)getDataSuccess:(id)responseObj
{
    [kApp hideWaitView];
    [self btnsEnable];
    
    if (!IsArray(responseObj)) {
        [self performSelector:@selector(goBack:) withObject:nil afterDelay:0.7];
        [PopTips tips:kApp.rootNav.view Msg:@"大侠，片子有点不给力"];
        return;
    }
   
    NSArray* arr = responseObj;
    
    self.scoreBtn.enabled = YES;
    
    for (NSDictionary* dic in arr) {
        VideoObj* videoObj = [[VideoObj alloc]init];
        videoObj.episodeId = [dic objectForKey:@"id"];
        videoObj.contentName = [dic objectForKey:@"title"];
        videoObj.type = [dic objectForKey:@"vtype"];
        videoObj.imageSrc = [dic objectForKey:@"pic"];
        videoObj.playURL = [dic objectForKey:@"url"];
        videoObj.director  = [dic objectForKey:@"director"];
        videoObj.length = [dic objectForKey:@"length"];
        videoObj.intro = [dic objectForKey:@"desc"];
        videoObj.releaseDate = [dic objectForKey:@"release_date"];
        videoObj.category = [dic objectForKey:@"type"];
        videoObj.picArray = [dic objectForKey:@"cont_pic"];
        videoObj.praiseNums = [dic objectForKey:@"praise_nums"];
        videoObj.isReadyShow = [[dic objectForKey:@"is_ok"] boolValue];
        [self.videoArray addObject:videoObj];
    }
    for (VideoObj* obj in self.videoArray) {
        if([obj.episodeId isEqualToString:self.videoObj.episodeId])
        {
            self.videoObj = obj;
            [self handleDetailWithVideoObj:self.videoObj];
            break;
        }
    }
    
}

-(void)getDataError
{
    [kApp hideWaitView];
    [PopTips tips:self.view Msg:NotifyNoNet];
    [self performSelector:@selector(goBack:) withObject:self afterDelay:0.7];
    return;
}





-(void)handleDetailWithVideoObj:(VideoObj*)videoObj
{
    UILabel* titleLabel = (UILabel*)[self.infoView viewWithTag:200];
    UILabel* directorLabel = (UILabel*)[self.infoView viewWithTag:202];
    UILabel* lengthLabel = (UILabel*)[self.infoView viewWithTag:203];
    UILabel* typeLabel = (UILabel*)[self.infoView viewWithTag:204];
    UILabel* dateLabel = (UILabel*)[self.infoView viewWithTag:205];
    UIImageView* imageView = (UIImageView*)[self.infoView viewWithTag:302];
    imageView.layer.borderWidth = 1.0f;
    imageView.layer.borderColor = RGB(5, 47, 70).CGColor;
    UILabel* scoreLabel = (UILabel*)[self.infoView viewWithTag:206];
    
    if([UserDataBasic getObjectForKey:self.videoObj.episodeId])
    {
        self.scoreBtn.enabled = NO;
    }
    
    
    titleLabel.text = videoObj.contentName;
    directorLabel.text = videoObj.director;
    lengthLabel.text = videoObj.length;
    typeLabel.text = videoObj.category;
    dateLabel.text = videoObj.releaseDate;
    scoreLabel.text = videoObj.praiseNums;
    self.detailLabel.text = videoObj.intro;
    
    if(videoObj.isReadyShow)
    {
        self.playBtn.enabled = YES;
    }
    else{
        self.playBtn.enabled = NO;
    }
    
    [[AFGetData sharedInstance] initSDWebImage:videoObj.imageSrc andTrueImageView:imageView andPlaceholderImage:nil];
    
    [self.myCircleView drawContainerWithTotalNums:[self.videoObj.picArray count] andOrientation:CircleOrientationLandscape];
    
}

#pragma mark - 按钮的可点与不可点
-(void)btnsDisable
{
    self.shareBtn.enabled = NO;
    self.moreBtn.enabled = NO;
    self.playBtn.enabled = NO;
}

-(void)btnsEnable
{
    self.shareBtn.enabled = YES;
    self.moreBtn.enabled = YES;
    self.playBtn.enabled = YES;
}

#pragma mark - UICollectionView methods
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
            return self.recommendArray.count;
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellIdentifier =CellIdentifer;
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    
    UILabel *titleLabel=(UILabel *)[cell viewWithTag:200];
    UIImageView* imageView = (UIImageView*)[cell viewWithTag:302];
    
    NSDictionary* dic = [self.recommendArray objectAtIndex:indexPath.row];
    titleLabel.text = [dic objectForKey:@"name"];
    [[AFGetData sharedInstance] initSDWebImage:[dic objectForKey:@"pic"] andTrueImageView:imageView andPlaceholderImage:nil];
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSDictionary* dic = [self.recommendArray objectAtIndex:indexPath.row];
    
    [self goToAppStoreWithAppId:[dic objectForKey:@"url"]];
    [Common getWYByPostWithType:@"6" andItemId:@"0"];
}

#pragma mark - goToAppstore
-(void)goToAppStoreWithAppId:(NSString*)appId
{
   
    [kApp displayWaitViewWithAllMaskView:NO];
    //初始化控制器
    SKStoreProductViewController *storeProductViewContorller = [[SKStoreProductViewController alloc] init];
    //设置代理请求为当前控制器本身
    storeProductViewContorller.delegate = self;
    //加载一个新的视图展示
    [storeProductViewContorller loadProductWithParameters:
     //appId唯一的
     @{SKStoreProductParameterITunesItemIdentifier : appId} completionBlock:^(BOOL result, NSError *error) {
         //block回调
         if(error){
             [kApp hideWaitView];
         }else{
             //模态弹出appstore
             [self presentViewController:storeProductViewContorller animated:YES completion:^{
                 [kApp hideWaitView];
             }
              ];
         }
     }];
    
}

//取消按钮监听
- (void)productViewControllerDidFinish:(SKStoreProductViewController *)viewController{
   
    [kApp hideWaitView];
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}

#pragma mark - CircleScrollViewDelegate
-(void)circleScrollView:(UIScrollView *)scrollView refreshThePageWithIndexArray:(NSArray *)indexArray
{
   
    for (int i = 0; i<indexArray.count; i++) {
        UIView* pageView = [scrollView.subviews objectAtIndex:i];
        int index = (int)[[indexArray objectAtIndex:i] integerValue];
        
        UIImageView* imageView = (UIImageView*)[pageView viewWithTag:302];
        UIButton* btn = (UIButton*)[pageView viewWithTag:201];
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [[AFGetData sharedInstance] initSDWebImage:[self.videoObj.picArray objectAtIndex:index] andTrueImageView:imageView andPlaceholderImage:nil];
    }

}

-(void)btnClick:(id)sender
{
   
    if(self.isUp)
    {
        self.myScrollView.contentOffsetTop = 0;
        [self topBgViewDisappear];
        [self goDown];
    }
    else{
        [self topBgViewAppear];
        [self goUp];
    }
}

#pragma mark - UIScrollViewDelegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if([self.videoObj.picArray count] == 0||IsNull(self.videoObj.picArray))
    {
        return;
    }
    
    float sety = scrollView.contentOffsetTop;
    
    if(sety > 0)
    {
        [self topBgViewDisappear];
    }
    if(sety <=0)
    {
        [self topBgViewAppear];
       self.contentView.top = self.defaultContentTop + sety;
        if(sety <= -OffsetY) //超过80
        {
            if(scrollView.decelerating)
            {
                return;
            }
            
            if(scrollView.isDragging) //手还没松开
            {
                self.myScrollView.contentOffsetTop = -OffsetY;
                self.myScrollView.scrollEnabled = NO;
                [self topBgViewDisappear];
                [self goDown];
            }
        }
    }
}

-(void)topBgViewDisappear
{
    
    [UIView animateWithDuration:DefaultDur animations:^{
        self.topBgView.top = -64;
    } completion:^(BOOL finished) {
        
    }];
}

-(void)topBgViewAppear
{
    float y = isiOS7 ? 20 : 0;
    [UIView animateWithDuration:DefaultDur animations:^{
        self.topBgView.top = y;
    } completion:^(BOOL finished) {
        
    }];
    
    
}

-(void)specialAnimation
{
    [UIView animateWithDuration:0.1 animations:^{
        self.topBgView.top = -64;
    } completion:^(BOOL finished) {
        
    }];
}

#pragma mark - 下来
-(void)goDown
{
    [UIView animateWithDuration:DefaultDur delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.isDowning = YES;
        self.contentView.top = 0;
        self.mainView.top = self.view.height;
        self.topBgView.top = -64;
    } completion:^(BOOL finished) {
        self.isUp = NO;
        self.isDowning = NO;
        self.myScrollView.scrollEnabled = NO;

    }];
   }

#pragma mark - 上来
-(void)goUp
{
    [UIView animateWithDuration:DefaultDur delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.contentView.top = self.defaultContentTop;
        self.mainView.top = self.defaultScrollTop;
       
         self.topBgView.top = isiOS7 ? 20 : 0;
        
    } completion:^(BOOL finished) {
        self.isUp = YES;
        self.myScrollView.scrollEnabled = YES;
        
    }];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - xib点击事件
- (IBAction)goBack:(id)sender {
    [kApp hideWaitView];
    [[AFGetData sharedInstance] removeAllGetAndPostRequest];
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)goToShare:(id)sender {
    [kApp initShareViewWithUrl:ShareUrl andWithTitle:ShareTitle andWithInfo:NotifyRecommendShare andWithImageUlr:ShareImageUrl andIsSuccess:^(BOOL isSuccess) {
        if(isSuccess)
        {
            [PopTips tips:kApp.rootNav.view Msg:NotifyShareSuccess];
        }
        else{
            [PopTips tips:kApp.rootNav.view Msg:NotifyShareError];
        }
    }];

}
- (IBAction)play:(id)sender {
    
    self.isGoPlay = YES;
    [kHandle sharedInstance].videoPlayerVC = [[VideoPlayerViewController alloc]initWithNibName:@"VideoPlayerViewController" andObj:self.videoObj andListArray:self.videoArray];
    [self presentViewController:[kHandle sharedInstance].videoPlayerVC animated:YES completion:nil];
    if([self.videoObj.episodeId isEqualToString:@"1"])
    {
        [Common getWYByPostWithType:@"4" andItemId:@"0"];
    }
    if([self.videoObj.episodeId isEqualToString:@"2"]){
        [Common getWYByPostWithType:@"7" andItemId:@"0"];
    }
    
}
- (IBAction)moreBtnClick:(id)sender {
    self.moreBtn.selected = !self.moreBtn.selected;
    if(self.moreBtn.selected)
    {
        self.detailLabel.height = [Common handleTheLabelHeight:self.detailLabel withText:self.videoObj.intro withMaxHeight:50000];
            float tempHeight = self.detailLabel.height-self.detailLabelHeight;
            self.detailView.height += tempHeight;
            self.myScrollView.contentHeight += tempHeight;
            self.guessView.top = self.detailView.bottom;
    }
    else
    {
        
            float tempHeight = self.detailLabel.height - self.detailLabelHeight;
            self.detailLabel.height = self.detailLabelHeight;
                       self.detailView.height -= tempHeight;
            self.myScrollView.contentHeight -= tempHeight;
            self.guessView.top = self.detailView.bottom;

       }
   
}

- (IBAction)loveClick:(id)sender {
    UIButton* btn = (UIButton*)sender;
    btn.enabled = NO;
    self.scoreLabel.text = [NSString stringWithFormat:@"%d",[self.videoObj.praiseNums intValue]+1];
    [UserDataBasic setObject:@"1" forKey:self.videoObj.episodeId];
    [Common addScoreWithParentView:btn];
}


@end
